<template>
  <div>
    <searchBox @handleSearch="handleQuery" @handleReset="resetQuery">
      <el-form :model="queryParams.param" ref="queryForm" :inline="true">
        <el-form-item label="品牌名称" prop="commonName">
          <el-input v-model.trim="queryParams.param.commonName" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select style="width: 200px" v-model="queryParams.param.status" placeholder="请选择" clearable>
            <el-option v-for="(dict, index) in sys_status_type" :key="dict.index" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </searchBox>
    <el-button type="primary" @click="handleAdd" class="mb8">新增</el-button>

    <el-table :data="brandList" v-loading="listLoading">
      <el-table-column label="ID" prop="id" width="100" />
      <el-table-column label="LOGO" align="center" prop="logoImage" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.host" fit="scale-down" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="品牌名称" align="left" prop="commonName">
        <template #default="scope">
          <el-space spacer=" ">
            <el-tooltip effect="dark" :content="scope.row.commonName">
              <el-text truncated style="width: 100px">{{
                scope.row.commonName
              }}</el-text>
            </el-tooltip>

            <el-button link type="primary" size="small" @click="viewTranslate(scope.row)">查看翻译</el-button>
          </el-space>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="seq" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-switch :width="58" class="demo" v-model="scope.row.status" :active-value="1" :inactive-value="0"
            active-text="开启" inactive-text="关闭" :loading="loading" inline-prompt
            @change="handleStatusChange(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="newTime" />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button link type="primary" @click="handleUpdate(scope.row)">
            编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination :total="total" :limit="queryParams.pageSize" :page="queryParams.pageNum" @pagination="handlePageChange">
    </Pagination>

    <!-- 添加或修改品牌对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body @close="cancel">
      <el-form ref="BrandRef" :model="form" :rules="rules" label-width="80px">
        <el-col :span="18">
          <el-form-item label="通用名称" prop="commonName">
            <el-input v-model.trim="form.commonName" placeholder="请输入通用名称" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="排序" prop="seq">
            <el-input type="number" v-model.trim="form.seq" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-form-item label="状态" prop="status">
          <el-switch :width="58" class="demo" v-model="form.status" :active-value="1" :inactive-value="0"
            active-text="开启" inactive-text="关闭" inline-prompt />
        </el-form-item>

        <el-form-item label="LOGO" prop="newImage" required>
          <image-upload @baseUrl="handleBaseUrl" v-model="form.newImage" :limit="1" />
        </el-form-item>

        <el-divider content-position="center">品牌名称翻译管理</el-divider>
        <el-form-item prop="descriptions" required>
          <MoreLanguage :newList="form.descriptions" label="品牌名称" @publicCheck="publicCheck"></MoreLanguage>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="footer_box">
          <el-button type="primary" @click="handleAddBrandDescription">添加</el-button>
          <el-button type="danger" @click="handleDeleteBrandDescription" style="margin-right: 450px">删除</el-button>

          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <Translation :dialogVisible="openViewTranslate" :languageList="translateData" name="anotherName"
      @handleTranslationClose="handleTranslationClose"></Translation>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
const { proxy } = getCurrentInstance();
const loading = ref(false);
const { sys_status_type } = proxy.useDict("sys_status_type");
const checkedBrandDescription = ref([]); // 子表选中数据
const total = ref(0); // 总条数
const brandList = ref([]); // 品牌管理表格数据
const title = ref(""); // 弹出层标题
const open = ref(false); // 是否显示弹出层
const listLoading = ref(true); // 列表加载loading



// 表单校验
const rules = ref({
  commonName: [
    { required: true, message: "品牌名称不能为空", trigger: "blur" },
  ],
  logoImage: [{ required: true, message: "品牌LOGO不能为空", trigger: "blur" }],
  seq: [{ required: true, message: "序号不能为空", trigger: "blur" }],
  descriptions: [{ required: true, message: "请填写", trigger: "blur" }],
  newImage: [{ required: true, message: "请选择", trigger: "blur" }],
});

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  param: {
    commonName: "",
    status: null,
  },
});
// 表单参数
const form = ref({
  commonName: "", //品牌通用名称
  seq: 0,
  logoImage: "", //LOGO
  status: 1,
  descriptions: [], //languageId   anotherName
  newImage: "", //需要删除
});

const translateData = ref([]);
const publicItem = ref({}); //公共赋值对象
const openViewTranslate = ref(false); // 翻译弹窗
// 表格状态控制
const handleStatusChange = (e) => {
  loading.value = true;
  proxy.$modal
    .confirm("是否确认修改此数据的状态？")
    .then(() => {
      return product.brand
        .brandUpdatestatus({
          pathParams: {
            id: e.id,
          },
          params: {
            status: e.status,
          },
        })
        .then((response) => {
          loading.value = false;
          proxy.$modal.msgSuccess("修改状态成功");
          getList();
        });
    })
    .catch(() => {
      loading.value = false;
      if (e.status) {
        return (e.status = 0);
      } else {
        return (e.status = 1);
      }
    });
};
// 查看翻译
const viewTranslate = (rowItem) => {
  product.brand
    .getById({
      pathParams: {
        id: rowItem.id,
      },
    })
    .then((res) => {
      openViewTranslate.value = true;
      translateData.value = res.data.brandDescriptionList;
    });
};

/** 查询品牌管理列表 */
const getList = () => {
  product.brand
    .list({
      data: queryParams.value,
    })
    .then((response) => {
      listLoading.value=false
      response.data = response.data?.map((code) => {
        return {
          ...code,
          newTime: proxy.DateTime(code.lastModified),
        };
      });
      brandList.value = response.data;
      total.value = response.total;
    });
};
// 取消按钮
const cancel = () => {
  open.value = false;
  reset();
};
// 表单重置
const reset = () => {
  form.value = {
    commonName: "", //品牌通用名称
    seq: 0,
    logoImage: "", //LOGO
    status: 1,
    descriptions: [], //languageId   anotherName
  };
  proxy.resetForm("BrandRef");
};
/** 添加红色星星 */
const addRedStar = ({ column }) => {
  return [
    h("span", { style: "color: red" }, "*"),
    h("span", " " + column.label),
  ];
};
/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  proxy.resetForm("queryForm");
  handleQuery();
};

/** 新增按钮操作 */
const handleAdd = () => {
  publicItem.value = {};
  open.value = true;
  title.value = "添加品牌管理";
  form.value.descriptions.push({
    languageId: 1,
    name: "",
  });
};
/** 修改按钮操作 */
const handleUpdate = (rowItem) => {
  publicItem.value = rowItem;
  product.brand
    .getById({
      pathParams: {
        id: rowItem.id,
      },
    })
    .then((res) => {
      if (res.code === 200) {
        open.value = true;
        title.value = "修改品牌管理";
        form.value.commonName = res.data.commonName;
        form.value.seq = res.data.seq;
        form.value.newImage = res.data.host;
        form.value.logoImage = res.data.logoImage;
        form.value.status = res.data.status;
        form.value.descriptions = res.data.commonBrandDescriptionList?.map((code) => {
          return {
            languageId: code.languageId,
            name: code.anotherName,
          };
        });
      }
    });
};
/** 提交按钮 */
const submitForm = () => {
  console.log(form.value.descriptions, "提交按钮");
  proxy.$refs["BrandRef"].validate((valid) => {
    if (valid) {
      if (!proxy.publicArray(form.value.descriptions))
        return proxy.$modal.msgError("请完整填写新增语言");
      form.value.descriptions.forEach((code) => {
        code.anotherName = code.name;
      });

      if (Object.keys(publicItem.value).length) {
        // console.log("走到则会一部");
        product.brand
          .brandUpdate({
            pathParams: {
              id: publicItem.value.id,
            },
            data: form.value,
          })
          .then((res) => {
            if (res.code !== 200) return;
            proxy.$modal.msgSuccess("修改成功");
            cancel();
            getList();
          });
      } else {
        product.brand
          .brandAdd({
            data: form.value,
          })
          .then((res) => {
            if (res.code !== 200) return;
            proxy.$modal.msgSuccess("新增成功");
            cancel();
            getList();
          });
      }
    }
  });
};
/** 删除按钮操作 */
const handleDelete = (row) => {
  proxy.$modal.confirm("是否确认删除此数据项？").then(function () {
    return product.brand
      .brandDeletebatch({
        data: {
          ids: [row.id],
        },
      })
      .then((res) => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
      });
  });
};

/** 品牌详情添加按钮操作 */
const handleAddBrandDescription = () => {
  var obj = {
    languageId: null,
    name: "",
    // anotherName: "",//真实name字段记得赋值
  };
  form.value.descriptions.push(obj);
};
/** 品牌详情删除按钮操作 */
const handleDeleteBrandDescription = () => {
  if (checkedBrandDescription.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的品牌详情数据");
  } else {
    form.value.descriptions = form.value.descriptions.filter(
      (item) => !checkedBrandDescription.value.includes(item.index)
    );
    checkedBrandDescription.value = [];
  }
};
/** 复选框选中数据 */
const publicCheck = (rowList) => {
  checkedBrandDescription.value = rowList;
};

onMounted(() => {
  getList();
});
// 分页
const handlePageChange = (newPage) => {
  searchFrom.value.pageNum = newPage.page;
  searchFrom.value.pageSize = newPage.limit;
  getList();
};

// 照片的host赋值
const handleBaseUrl = (val) => {
  form.value.logoImage = val.url;
};
const handleTranslationClose = () => {
  openViewTranslate.value = false;
};
</script>
<style lang="scss" scoped>
.footer_box {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>